//
//  PywCommonManager.m
//  PywSdk
//
//  Created by smallwave on 16/4/23.
//  Copyright © 2016年 zero. All rights reserved.
//

#import <AssetsLibrary/ALAssetsLibrary.h>
#import <CoreLocation/CLLocationManager.h>
#import "PywCommonManager.h"
#import "PywMBProgressHUD+Pyw.h"
#import "PywSdk+login.h"
#import "PywCPNotifications.h"
#import <Photos/Photos.h>

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

@interface PywCommonManager ()<UIAlertViewDelegate>

@end

@implementation PywCommonManager

+ (id)manager{
    
    static id manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}


- (void)printScreenAndSavePhoto:(SaveAlbumComplete)saveAlbumComplete
{
    self.saveAlbumComplete = saveAlbumComplete;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
        ALAuthorizationStatus author =[ALAssetsLibrary authorizationStatus];
        if (author == kCLAuthorizationStatusRestricted || author == kCLAuthorizationStatusDenied) {
            //无权限
            PLog(@"ios8前 无权限");
            NSString *tips = [NSString stringWithFormat:@"需要设置“允许”应用访问您的照片"];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:tips delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            alert.delegate = self;
            [alert show];
        } else {
            // 截图
            UIImage *screenImage = [self getImageWithFullScreenshot];
            
            // 耗时操作
            dispatch_queue_t queue = dispatch_queue_create("concurrent", DISPATCH_QUEUE_CONCURRENT);
            dispatch_async(queue, ^{
                [self saveToAlbum:screenImage];
            });
        }
    } else {
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusRestricted ||
            status == PHAuthorizationStatusDenied) {
            //无权限
            PLog(@"ios8后 无权限");
            NSString *tips = [NSString stringWithFormat:@"需要设置“允许”应用访问您的照片"];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:tips delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            alert.delegate = self;
            [alert show];
            
        } else {
            // 截图
            UIImage *screenImage = [self getImageWithFullScreenshot];
            
            // 耗时操作
            dispatch_queue_t queue = dispatch_queue_create("concurrent", DISPATCH_QUEUE_CONCURRENT);
            dispatch_async(queue, ^{
                [self saveToAlbum:screenImage];
            });
        }
    }
}

#pragma mark - printScreen private method
/**
 *  截图
 *
 *  @return return value description
 */
- (UIImage *)getImageWithFullScreenshot
{
    
    BOOL ignoreOrientation = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0");
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    CGSize imageSize = CGSizeZero;
    if (UIInterfaceOrientationIsPortrait(orientation) || ignoreOrientation)
        imageSize = [UIScreen mainScreen].bounds.size;
    else
        imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
    
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    for (UIWindow *window in [[UIApplication sharedApplication] windows])
    {
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, window.center.x, window.center.y);
        CGContextConcatCTM(context, window.transform);
        CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
        
        // Correct for the screen orientation
        if(!ignoreOrientation)
        {
            if(orientation == UIInterfaceOrientationLandscapeLeft)
            {
                CGContextRotateCTM(context, (CGFloat)M_PI_2);
                CGContextTranslateCTM(context, 0, -imageSize.width);
            }
            else if(orientation == UIInterfaceOrientationLandscapeRight)
            {
                CGContextRotateCTM(context, (CGFloat)-M_PI_2);
                CGContextTranslateCTM(context, -imageSize.height, 0);
            }
            else if(orientation == UIInterfaceOrientationPortraitUpsideDown)
            {
                CGContextRotateCTM(context, (CGFloat)M_PI);
                CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
            }
        }
        
        if([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
            [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:NO];
        else
            [window.layer renderInContext:UIGraphicsGetCurrentContext()];
        
        CGContextRestoreGState(context);
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}
/**
 *  保存图片
 *
 *  @param image <#image description#>
 */
- (void)saveToAlbum:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
         [PywMBProgressHUD showSuccess:@"账号信息截图保存失败！"];
    } else {
        [PywMBProgressHUD showSuccess:@"账号信息截图已经保存到了相册↖(^ω^)↗"];
    }
    [self performSelector:@selector(delayMethod) withObject:nil afterDelay:1.0f];
}
/**
 *  延时处理回调
 */
- (void)delayMethod{
    if (self.saveAlbumComplete) {
        self.saveAlbumComplete();
    }
}
/**
 *  修改WebViewUser-Agnet
 */
- (void)changeWebViewUserAgnet
{
    //get the original user-agent of webview
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    //    NSLog(@"old agent :%@", oldAgent);
    
    //add my info to the new agent
    NSString *newAgent = [oldAgent stringByAppendingString:@"app"];
    //    NSLog(@"new agent :%@", newAgent);
    
    //regist the new agent
    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
}

#pragma mark - timer Or enableBtn
- (void)startTimeWithButton:(UIButton *)button{
    __block int timeout = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (timeout <= 0) {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [button setTitleColor:RGB(252, 171, 15, 1) forState:UIControlStateNormal];
                [button setTitle:@"获取验证码" forState:UIControlStateNormal];
                button.userInteractionEnabled = YES;
            });
        }else{
            NSString *strTime = [NSString stringWithFormat:@"%.2d",timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
                [button setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];
                button.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
- (void)enableOrDisableWithButton:(UIButton *)button{
    __block int timeout = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (timeout <= 0) {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                button.userInteractionEnabled = YES;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                button.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

#pragma mark - regular dispose
- (BOOL)validatePhone:(NSString *)phone{

    if (phone.length != 11)
    {
        return NO;
    }
    
    NSString *MOBILE = @"^1\\d{10}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    if ([regextestmobile evaluateWithObject:phone] == YES){
        return YES;
    } else {
        return NO;
    }
}

#pragma mark - ChangeDevice Show
- (CGFloat)changeDeviceTextFontSize:(CGFloat)fontSize
{
    if (IS_IPAD || IS_IPHONE_6P) {
        fontSize = fontSize *1.3    ;
    }
    return fontSize;
}

@end
